#include "pch.h"
#include "tools.h"


UCHAR charToHex(UCHAR * ch)
{
	unsigned char temps[2] = { 0 };
	for (int i = 0; i < 2; i++)
	{
		if (ch[i] >= '0' && ch[i] <= '9')
		{
			temps[i] = (ch[i] - '0');
		}
		else if (ch[i] >= 'A' && ch[i] <= 'F')
		{
			temps[i] = (ch[i] - 'A') + 0xA;
		}
		else if (ch[i] >= 'a' && ch[i] <= 'f')
		{
			temps[i] = (ch[i] - 'a') + 0xA;
		}
	}
	return ((temps[0] << 4) & 0xf0) | (temps[1] & 0xf);
}


void initFindCodeStruct(PFindCode findCode, PCHAR code, ULONG offset, ULONG lastAddrOffset)
{

	memset(findCode, 0, sizeof(FindCode));

	findCode->lastAddressOffset = lastAddrOffset;
	findCode->offset = offset;
	
	PCHAR pTemp = code;
	int i = 0;
	for (i = 0; *pTemp != '\0'; i++)
	{
		if (*pTemp == '*' || *pTemp == '?')
		{
			findCode->code[i] = *pTemp;
			pTemp++;
			continue;
		}

		findCode->code[i] = charToHex((unsigned char*)pTemp);
		pTemp += 2;

	}

	findCode->len = i;
}


ULONG findAddressByCode(ULONG beginAddr, ULONG endAddr,PFindCode  findCode, ULONG size)
{
	int j = 0;
	ULONG rtna = 0;

	for (int i = beginAddr; i <= endAddr; i++)
	{
		if (IsBadReadPtr((PVOID)i,1))continue;
		
		//if (((ULONG)i) == 0x80588b7e + 5 && findCode[0].code[0] == 0x8B && size == 1) __asm int 3;

		for (j = 0; j < size; j++)
		{
			FindCode  fc = findCode[j];
			ULONG tempAddress = i;
			
			UCHAR * code = (UCHAR *)(tempAddress + fc.offset);
			BOOLEAN isFlags = FALSE;

			for (int k = 0; k < fc.len; k++)
			{
				if (IsBadReadPtr((PVOID)(code+k),1))
				{
					isFlags = TRUE;
					break;
				}

				if (fc.code[k] == '*' || fc.code[k] == '?') continue;

				if (code[k] != fc.code[k])
				{
					isFlags = TRUE; 
					break;
				}
			}

			if (isFlags) break;
			
		}

		//�ҵ���
		if (j == size)
		{
			rtna = i + findCode[0].lastAddressOffset;
			break;
		}

	}

	return rtna;
}



ULONG calcE8OrE9(ULONG oldAddr, ULONG newAddr)
{
	return newAddr - oldAddr - 5;
}


ULONG GetFunctionAddressByCodeAddress(ULONG addr)
{
	
	ULONG nextAddr = addr + 5;
	ULONG code = *(PULONG)(addr + 1);
	//��ú�����ַ
	return (code + nextAddr);
}


